package com.zhengbing.tj.listener;

import com.zhengbing.tj.service.LoginRecordService;
import com.zhengbing.tj.service.UserService;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Resource
    private UserService userService;

    @Resource
    private LoginRecordService loginRecordService;

    private static final Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        // 监听登录token的过期事件，假设token的key格式为：login:token:{userId}
        if (expiredKey.startsWith("login:token:")) {
            try {
                // 解析用户ID
                String userId = expiredKey.split(":")[2];
                // 更新用户登录记录为登出状态
                loginRecordService.recordLogout(Long.parseLong(userId));
            } catch (Exception e) {
                logger.error("处理token过期事件失败，key:{}", expiredKey, e);
            }
        }
    }


}